import {Image, StyleSheet, View, Text, TouchableOpacity, ImageBackground, FlatList, Animated, RefreshControl, ActivityIndicator} from 'react-native';
import {Stack, useRouter} from "expo-router";
import { scaleSize } from "@/utils/screenSize"
import AntDesign from '@expo/vector-icons/AntDesign';
import { Ionicons } from '@expo/vector-icons';
import {useEffect, useImperativeHandle, useState} from "react";
import addressIcon from "@/assets/images/collection/address.png"
import dateTimeIcon from "@/assets/images/collection/dateTime.png"
import empty_icon from "@/assets/images/concern/empty_fan.png"
import activityTag from "@/assets/images/collection/activityTag.png"
import groupActivityTagIcon from "@/assets/images/activityImg/groupActivityTagIcon.png"
import ActivityIntroModalComponent from "@/components/activityIntroModalComponent/index"
import {useSelector} from "react-redux";
import {RootState} from "@/store";
import {getSearchKeyWordListRequest} from "@/services/activityServices";
import {format} from "date-fns/index";
import {parseFloat} from "@/utils";
import Empty from "@/components/empty";
import * as React from "react";

export default function activityComponent({ detail }) {
    console.log('detail', detail);
    const [data, setData] = useState([]);
    const [loading, setLoading] = useState(false);
    const [refreshing, setRefreshing] = useState(false);
    const [triggerRefresh, setTriggerRefresh] = useState(false);
    const [page, setPage] = useState(1);
    const [refreshingText, setRefreshingText] = useState('下拉刷新');
    const scrollY = new Animated.Value(0);
    const [current, setCurrent] = useState(1);
    const [size, setSize] = useState(5);
    const [pages, setPages] = useState(0);
    const [noMore, setNoMore] = useState(false);

    const login = useSelector((state: RootState) => state.login);

    const router = useRouter();

    const goActivityDetail = function (id) {
        router.push(`/activityDetail/${id}`)
    };

    useEffect(() => {
        setData(detail?.activityList)
    }, [])

    // const getList = function (params?:any = {}) {
    //     console.log('params', params);
    //     const requestData = {
    //         province: login?.locationInfo?.province ||"",
    //         city: login?.locationInfo?.city || "",
    //         current: 1,
    //         size: 5,
    //         ...params,
    //     };
    //
    //     console.log('requestData', requestData);
    //
    //
    //     setLoading(true);
    //     getSearchKeyWordListRequest(requestData)
    //         .then((res) => {
    //             console.log('getSearchKeyWordListRequest', res);
    //             if (requestData?.current == 1) {
    //                 setData([...res?.data?.items]);
    //             } else {
    //                 setData([...data, ...res?.data?.items]);
    //             };
    //
    //             setPages(res?.data?.pages);
    //             setCurrent(res?.data?.current);
    //             setLoading(false);
    //             setRefreshing(false)
    //         })
    //         .catch(err => {
    //             setRefreshing(false);
    //             console.log('err', err);
    //         })
    // };

    useEffect(() => {
        // getList();
    }, [])

    // 自定义加载图标组件
    const RefreshControlHeader = ({ refreshing, text }) => (
        refreshing && (
            <View style={styles.refreshHeader}>
                <Text style={styles.refreshText}>{text}</Text>
            </View>
        )
    );

    useEffect(() => {
        if (triggerRefresh) {
            handleRefresh();
            setTriggerRefresh(false); // Reset trigger
        }
    }, [triggerRefresh]);

    const loadMoreData = () => {
        if (loading) return;

        setLoading(true);
        if (current === pages) {
            setLoading(false)
            setNoMore(true)
            return;
        };
        // 模拟网络请求来获取更多数据
        const params = {
            current: current + 1,
        }
        // getList(params)
    };

    const handleRefresh = () => {
        setRefreshing(true);
        setRefreshingText('正在刷新...');
        setPage(1);
        // getList({ current: 1 })
    };


    const renderFooter = () => {
        if (!loading) return null;
        if (data?.length <= 0) return null;
        return (
            <>
                {
                    loading && (
                        <View style={{ paddingVertical: 10, flexDirection: "row", justifyContent: "center", alignItems: "center" }}>
                            <ActivityIndicator size="small" />
                            <Text style={{ textAlign: 'center', fontSize: 14, color: "#676978", marginLeft: 5, }}>疯狂加载中</Text>
                        </View>
                    )
                }
            </>
        );
    };




    const handleScroll = Animated.event(
        [{ nativeEvent: { contentOffset: { y: scrollY } } }],
        {
            useNativeDriver: false,
            listener: event => {
                const offsetY = event.nativeEvent.contentOffset.y;

                if (!refreshing) {
                    // 根据下拉距离更新文本
                    if (offsetY < -100) {
                        setRefreshingText('松开刷新'); // 超过 -100 的偏移量显示松开刷新
                    } else if (offsetY < 0) {
                        setRefreshingText('下拉刷新'); // 在 -100 到 0 之间时显示下拉刷新
                    }
                }
            },
        }
    );

    const onScrollEnd = () => {
        scrollY.addListener(({ value }) => {
            if (!refreshing && value < -100) {
                setTriggerRefresh(true); // 触发刷新
            }
        });
    };

    const computedTime = function (startT, endT) {
        // console.log('startT', startT);
        // if (!isValid(startT) || !isValid(endT)) return  "";
        const day1 = format(startT, "yyMMdd");
        const day2 = format(endT, "yyMMdd");
        if (day1 == day2) {
            return `${format(startT, "MM.dd")} ${format(startT, "mm:ss")}-${format(endT, "mm:ss")}`
        };
        return `${format(startT, "MM.dd")} ${format(startT, "mm:ss")}-${format(startT, "MM.dd")} ${format(endT, "mm:ss")}`
    };



    const ActivityItem = ({ item }) => {
        return (
            <TouchableOpacity onPress={() => goActivityDetail(item?.activityId)}>
                <View style={styles.activityContainer}>
                    <View style={styles.activitybody}>
                        <View style={styles.activityBanner}>
                            <Image source={{ uri: item?.coverUrl }} style={{ width: "100%", height: "100%" }} />
                            <ImageBackground source={activityTag} style={styles.activityTagWarp}>
                                <Text style={styles.tagText}>{ item?.typeName }</Text>
                            </ImageBackground>

                        </View>
                        <View style={styles.activityContent}>
                            <View style={styles.activityTitleWarp}>
                                <Text
                                    style={styles.activityTitle}
                                    numberOfLines={2}
                                    ellipsizeMode="tail"
                                >{ item?.title }</Text>
                            </View>
                            <View style={{ flexDirection: "row" }}>
                                {
                                    item?.tags?.map((it: any, index: number) => {
                                        return (
                                            <View style={styles.activityTag} key={index}>
                                                <Text style={styles.activityTagText}>{ it }</Text>
                                            </View>
                                        )
                                    })
                                }
                            </View>

                            <View style={styles.activityDateWarp}>
                                <View style={styles.addressIcon}>
                                    <Image source={dateTimeIcon} style={{ width: '100%', height: "100%" }} />
                                </View>
                                <Text style={ styles.activityDate }>{ computedTime(item?.durationStartTime, item?.durationEndTime) }</Text>
                            </View>
                            <View style={styles.activityAdressWarp}>
                                <View style={styles.addressIcon}>
                                    <Image source={addressIcon} style={{ width: '100%', height: "100%" }} />
                                </View>
                                <Text style={[styles.activityAdress, { width: '75%' }]}>{ item?.destName }</Text>
                            </View>
                        </View>
                    </View>
                    <View style={styles.activityFooter}>
                        <View style={styles.joinList}>
                            <View style={styles.joinListWarp}>
                                {
                                    item?.members?.map((it:any, index: number) => {
                                        if (index == 0) {
                                            return (
                                                <View style={styles.joinAvator}>
                                                    <Image source={{ uri: it?.avator }} style={{ width: "100%", height: "100%" }} />
                                                </View>
                                            )
                                        } else if (index <= 3 ) {
                                            return (
                                                <View style={[styles.joinAvator,styles.maLeft]}>
                                                    <Image source={{ uri:it?.avator }} style={{ width: "100%", height: "100%" }} />
                                                </View>
                                            )
                                        }
                                    })
                                }

                            </View>
                            {
                                item?.activityStatus == 1 && (
                                    <View style={styles.joinContent}>
                                        <Text style={styles.joinContentText}>正在招募...</Text>
                                    </View>
                                )
                            }
                        </View>
                        <View style={styles.activityMoney}>
                            <Text style={styles.activityMoneyText}>¥{ parseFloat(item?.ticketsPrice) }</Text>
                        </View>
                    </View>
                </View>
            </TouchableOpacity>
        )
    };

    return (
        <View style={{ backgroundColor: "#F7F7F7", flex: 1 }}>
            <FlatList
                data={data}
                renderItem={({ item }) => <ActivityItem item={item}/>}
                keyExtractor={(item, index) => index.toString()}
                // onEndReached={loadMoreData}
                onEndReachedThreshold={0.5} // 当滚动到距离底部还有50%的时候触发
                ListFooterComponent={renderFooter}
                refreshControl={
                    <RefreshControl
                        refreshing={refreshing}
                        // onRefresh={handleRefresh} // 绑定刷新函数
                        title={refreshing ? '' : refreshingText} // 在正在刷新状态时不显示文本
                        titleColor="#333" // 设置提示文字颜色
                        tintColor="transparent" // 隐藏刷新指示器
                    />
                }
                // onScroll={handleScroll}
                // onScrollEndDrag={onScrollEnd}
                ListHeaderComponent={<RefreshControlHeader refreshing={refreshing} text={refreshingText} />}
                ListEmptyComponent={<Empty title="空空如也～"/>}
            />
        </View>
    );
}

const styles = StyleSheet.create({
    activityContainer: {
        // flexDirection: "row",
        marginLeft: 12,
        marginRight: 12,
        height: scaleSize(164),
        backgroundColor: "#fff",
        borderRadius: 8,
        marginBottom: 12,
    },
    activitybody: {
        padding: 12,
        flexDirection: "row",

    },
    activityBanner: {
        position: "relative",
        width: scaleSize(110),
        height: scaleSize(110),
        backgroundColor: "blue",
        borderRadius: 4,
    },
    activityContent: {
        marginLeft: 10,
    },
    activityTitleWarp: {
        width: scaleSize(192),
    },
    activityTitle: {
        fontSize: 16,
        fontWeight: "bold",
        color: "#2A2B30",
        letterSpacing: 1.2,
        lineHeight: 22,
    },
    addressIcon: {
        width: scaleSize(11),
        height: scaleSize(11),
    },
    activityTag: {
        width: scaleSize(28),
        height: scaleSize(12),
        backgroundColor: "rgba(255,70,0,0.1)",
        borderRadius: 10,
        marginTop: 6,
    },
    activityTagText: {
        fontSize: 8,
        color: "#EC6138",
        textAlign: "center",
        lineHeight: 12,
    },
    activityDateWarp: {
        flexDirection: "row",
        alignItems: "center",
        marginTop: 6,
        marginBottom: 6,
    },
    activityDate: {
        marginLeft: 3,
        fontSize: 12,
        color: "#676978"
    },
    activityAdressWarp: {
        flexDirection: "row",
        alignItems: "center",
    },
    activityAdress: {
        fontSize: 12,
        color: "#676978",
        marginLeft: 3,
    },
    joinList: {
        flexDirection: "row",
        alignItems: "center",
    },
    activityFooter: {
        flexDirection: "row",
        paddingLeft: 12,
        paddingRight: 12,
        justifyContent: "space-between",
        alignItems: "center"
    },
    joinAvator: {
        width: scaleSize(20),
        height: scaleSize(20),
        backgroundColor: "red",
        borderRadius: 10,
        borderColor: "#fff",
        borderWidth: 1,
    },
    maLeft: {
        marginLeft: -7,
    },
    joinListWarp: {
        flexDirection: "row",
    },
    joinContent: {
        marginLeft: 10,
    },
    joinContentText: {
        color: "#333",
        fontSize: 12,
        fontWeight: "bold"
    },
    activityMoney: {
        width: 56,
        height: 24,
        // backgroundColor: "#EC6138",
        borderRadius: 12,
        flexDirection: "row",
        justifyContent: "center",
        alignItems: "center"
    },
    activityMoneyText: {
        color: "#EC6138",
        fontSize: 18,
    },
    activityTagWarp: {
        position: "absolute",
        width: 30,
        height: 16,
        // backgroundColor: "red",
    },
    tagText: {
        fontSize: 10,
        textAlign: "center",
        color: "#fff",
        marginTop: 1,
    },
    refreshHeader: {
        alignItems: 'center',
        padding: 20,
    },
    refreshIcon: {
        width: 12,
        height: 12,
        marginBottom: 10,
    },
    refreshText: {
        fontSize: 12,
        color: '#333',
    },
});
